package com.graduation.fq.student.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.graduation.fq.student.Args.CourseCheckEventArgs;
import com.graduation.fq.student.Args.EventArgs;
import com.graduation.fq.student.Args.SimpleEventArgs;
import com.graduation.fq.student.Logic.ChooseLogic;
import com.graduation.fq.student.Logic.CourseCheckLogic;
import com.graduation.fq.student.R;
import com.graduation.fq.student.Utils.CommonUtils;
import com.graduation.fq.student.Utils.Const;
import com.graduation.fq.student.domain.CourseVO;
import com.graduation.fq.student.interfaces.EventListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by jifang
 * Time 2016/5/29 22:09.
 */
public class ChooseActivity extends Activity {
    private List<CourseVO> courseVOList;
    private CourseAdapter adapter;
    private ChooseLogic logic;
    private EditText creditInput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_layout);
        logic = ChooseLogic.getInstance();

        ListView courseListView = (ListView) findViewById(R.id.course_list_view);
        TextView allCourse = (TextView) findViewById(R.id.course_list_all);
        TextView creditCourse = (TextView) findViewById(R.id.course_list_credit);
        creditInput = (EditText) findViewById(R.id.course_list_credit_input);

        allCourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (creditInput.getVisibility() != View.INVISIBLE) {
                    creditInput.setVisibility(View.INVISIBLE);
                }
                getCourseList();
            }
        });
        creditCourse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (creditInput.getVisibility() != View.VISIBLE) {
                    creditInput.setVisibility(View.VISIBLE);
                } else {
                    getCourseListByCredit(creditInput.getText().toString());
                }
            }
        });
        initListView(courseListView);
        getCourseList();
    }

    private void getCourseListByCredit(String s) {
        if (TextUtils.isEmpty(s)) {
            Toast.makeText(this, "请输入学分", Toast.LENGTH_SHORT).show();
        } else {
            int credit = Integer.parseInt(s);
            CourseCheckLogic logic = CourseCheckLogic.getInstance();
            logic.getCourseByCredit(credit, new EventListener() {
                @Override
                public void onEvent(EventArgs args) {
                    int status = args.getStatus();
                    if (status == Const.HTTP_SUCCESS) {
                        CourseCheckEventArgs args1 = (CourseCheckEventArgs) args;
                        courseVOList.clear();
                        courseVOList.addAll(args1.getCourses());
                        adapter.notifyDataSetChanged();
                        creditInput.getText().clear();
                    }
                }
            });
        }
    }

    private void getCourseList() {
        CourseCheckLogic logic = CourseCheckLogic.getInstance();
        logic.getAllCourse(new EventListener() {
            @Override
            public void onEvent(EventArgs args) {
                int status = args.getStatus();
                if (status == Const.HTTP_SUCCESS) {
                    CourseCheckEventArgs checkEventArgs = (CourseCheckEventArgs) args;
                    courseVOList.clear();
                    courseVOList.addAll(checkEventArgs.getCourses());
                    adapter.notifyDataSetChanged();
                }
            }
        });

    }

    /**
     * 初始化 ListView
     *
     * @param courseListView
     */
    private void initListView(final ListView courseListView) {
        courseVOList = new ArrayList<>();
        adapter = new CourseAdapter();
        adapter.setCourseVOs(courseVOList);
        courseListView.setAdapter(adapter);

        courseListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CheckChoosed((CourseVO) parent.getAdapter().getItem(position), courseListView);
            }
        });
    }

    private void CheckChoosed(final CourseVO item, final ListView listView) {
        listView.setEnabled(false);
        final int uId = CommonUtils.getUserId(this);
        logic.isAdded(uId, item.getId(), new EventListener() {
            @Override
            public void onEvent(EventArgs args) {
                int status = args.getStatus();
                if (status == Const.HTTP_SUCCESS) {
                    boolean isAdded = ((SimpleEventArgs<Boolean>) args).getValue();
                    showSelectDialog(isAdded, item);
                    listView.setEnabled(true);
                }
            }
        });
    }

    private void showSelectDialog(boolean isAdded, final CourseVO item) {
        if (isAdded) {
            final AlertDialog cancelDialog = new AlertDialog.Builder(this).setTitle("此课程已经选择").setMessage("是否取消选择？").setNegativeButton("否", null).setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    cancelChoose(item);
                }
            }).create();
            cancelDialog.setCanceledOnTouchOutside(false);
            cancelDialog.show();
        } else {
            AlertDialog addDialog = new AlertDialog.Builder(this).setTitle("此课程还未选择").setMessage("是否选择此课程？").setNegativeButton("否", null).setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    addChoose(item);
                }
            }).create();
            addDialog.setCanceledOnTouchOutside(false);
            addDialog.show();
        }
    }

    private void addChoose(CourseVO item) {
        logic.add(CommonUtils.getUserId(this), item.getId());
    }

    /**
     * 取消选择这门课
     *
     * @param item
     */
    private void cancelChoose(CourseVO item) {
        logic.cancel(CommonUtils.getUserId(this), item.getId());
    }


    private class CourseAdapter extends BaseAdapter {
        private List<CourseVO> courseVOs;

        public void setCourseVOs(List<CourseVO> courseVOs) {
            this.courseVOs = courseVOs;
        }

        @Override
        public int getCount() {
            return courseVOs.size();
        }

        @Override
        public Object getItem(int position) {
            return courseVOs.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CourseVO course = courseVOs.get(position);
            CourseViewHolder holder = null;
            if (convertView == null) {
                holder = new CourseViewHolder();
                convertView = getLayoutInflater().inflate(R.layout.layout_course_list_item, null);
                holder.name = (TextView) convertView.findViewById(R.id.course_item_name);
                holder.credit = (TextView) convertView.findViewById(R.id.course_item_credit);
                holder.teacher = (TextView) convertView.findViewById(R.id.course_item_teacher);
                convertView.setTag(holder);
            } else {
                holder = (CourseViewHolder) convertView.getTag();
            }

            holder.name.setText(course.getName());
            holder.credit.setText(String.valueOf(course.getCredit()));
            holder.teacher.setText(course.gettName());

            return convertView;
        }
    }

    private class CourseViewHolder {
        TextView name;
        TextView credit;
        TextView teacher;
    }
}
